package cn.duli.xianer.utils;

import cn.leancloud.core.AVOSCloud;
import cn.leancloud.sms.AVSMS;
import cn.leancloud.sms.AVSMSOption;
import cn.leancloud.types.AVNull;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class SmsUtil {

    /**
     * leanCloud调用接口发送验证短信
     * @param phone
     * @return
     */

    // 发送短信状态
    static boolean smsStatus;

    public static boolean postMsg(String phone) {
        AVOSCloud.initialize("oKrIlmhg34Nn81yzsYJgricQ-gzGzoHsz", "DvN2BGaw16da6BXKpLVJJKf1");
        AVSMSOption option = new AVSMSOption();
        option.setTtl(10);
        option.setApplicationName("闲贰");
        option.setOperation("短信验证");
        AVSMS.requestSMSCodeInBackground(phone, option).subscribe(new Observer<AVNull>() {
            @Override
            public void onSubscribe(Disposable disposable) {
            }
            @Override
            public void onNext(AVNull avNull) {
                smsStatus = true;
                System.out.println("Result: Successfully sent verification code.");
            }
            @Override
            public void onError(Throwable throwable) {
                smsStatus = false;
                System.out.println("Result: Failed to send verification code. Reason: " + throwable.getMessage());
            }
            @Override
            public void onComplete() {

            }
        });
        return smsStatus;
    }

    /**
     * 调用接口验证用户输入的验证码是否有效
     * @param code
     * @param phone
     * @return
     */
    public static boolean verifyMsg(String code, String phone) {
        AVOSCloud.initialize("oKrIlmhg34Nn81yzsYJgricQ-gzGzoHsz", "DvN2BGaw16da6BXKpLVJJKf1");
        AVSMS.verifySMSCodeInBackground(code,phone).subscribe(new Observer<AVNull>() {
            @Override
            public void onSubscribe(Disposable d) {
            }
            @Override
            public void onNext(AVNull avNull) {
                smsStatus = true;
                System.out.println("Result: Successfully verified the number.");
            }
            @Override
            public void onError(Throwable throwable) {
                smsStatus = false;
                System.out.println("Result: Failed to verify the number. Reason: " + throwable.getMessage());
            }
            @Override
            public void onComplete() {
            }
        });
        return smsStatus;
    }

}
